package com.fingard.dsp.bank.directbank.boc01;

import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.dbobj.updownfile.DownFileHelper;
import com.fingard.dsp.bank.dbobj.updownfile.DownFileRecord;
import com.fingard.dsp.bank.directConfig.ReceiptProConfig;
import com.fingard.dsp.bank.directConfig.ReceiptSet;
import com.fingard.dsp.bank.directbank.bankInterface.IReceiptPro;
import com.fingard.dsp.bank.directbank.boc01.receiptpro.BOC01TaskReceiptPro;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class BOC01ReceiptPro extends BOC01Base implements IReceiptPro{

	@Override
	public RetAtsReceipt qryReceiptOneDay(ReceiptProConfig pConfig, ReqQryReceipt pReqReceipt, Date pOneDay)
			throws Exception {
		qryReceipt_b2e0500_b2e0377(pReqReceipt, pOneDay);
		
		return null;
	}
	
	/**2.47. 电子回单下载(b2e0377)
基础金融服务类交易
支持单一企业；银企对接客户可通过此功能下载电子回单明细信息，ctis将文件放到
SFTP服务器中，SFTP服务器收到文件后会向前置机发送通知，前置机收到通知后去服务器中
获取该文件，客户可在前置机中获得下载文件；前置机也可定时查找服务器中是否存在下载文
件，如存在将文件下载到前置机中；支持市场细分5
1） 起始日期和截止日期满足跨度3个月，范围为一年内；*/

	/**2.61. 逐笔电子回单下载(b2e0500)
基础金融服务类交易
业务说明：支持集团客户（以主办企业下载协办企业），每笔交易对应一个电子回单文件
（PDF格式），整体文件且每个电子回单的文件名包含日期、账号和交易流水号，并且此三个
要素能够在交易明细报文中返回，实现电子回单和交易明细的精确匹配。
技术接入流程：银企对接客户可通过此功能下载逐笔电子回单明细信息，ctis将文件放到
SFTP服务器中，SFTP服务器收到文件后会向前置机发送通知，前置机收到通知后去服务器中
获取该文件，客户可在前置机中获得下载文件；前置机也可定时查找服务器中是否存在下载文
件，如存在将文件下载到前置机中；支持市场细分5,1） 起始日期和截止日期满足跨度1天，范
围为一年内；*/
	
	/**b2e0500逐笔，银行返回压缩包，解压之后一个回单一个pdf；
	 * b2e0377汇总，银行返回一个pdf，里面是所有的回单；
	 * 建议采用b2e0500逐笔接口*/
	public void qryReceipt_b2e0500_b2e0377(ReqQryReceipt p_reqReceipt, Date pOneDay) {
		try {
			String receiptTrnCode = this.getBankConfig().getValueAsString("receiptTrnCode").toLowerCase();
			//回单接口b2e0377,b2e0500，二选一，默认b2e0500（逐笔）
			if(!"b2e0377".equals(receiptTrnCode)){
				receiptTrnCode = "b2e0500";
			}
			ReceiptSet receiptSet = this.getBankReceiptConfig().getReceiptSetByAct(p_reqReceipt.actNum, bankFront);
			BOC01Header bankHeader = new BOC01Header();
	        bankHeader.trncod = receiptTrnCode;//交易代码
	        bankHeader.trnid = getQryTransID();//报文编号 字母数字串 0-12位
	        bankHeader.orgOverride = receiptSet.org;
	        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
	        //写入通用的头部节点
	        writeCommonHeader(xmlWriter, bankHeader);
	        xmlWriter.writeStartElement("trn-"+receiptTrnCode+"-rq");//trn-b2e0500-rq trn-b2e0377-rq
	        xmlWriter.writeStartElement(receiptTrnCode+"-rq");
	        xmlWriter.writeElementString("tratype", "A");//交易类型A-全部

	        xmlWriter.writeStartElement("amtscope");
	        xmlWriter.writeElementClosed("minamt");//金额下限
	        xmlWriter.writeElementClosed("maxamt");//金额上限
	        xmlWriter.writeEndElement();

	        xmlWriter.writeStartElement("datescope");
	        xmlWriter.writeElementString("from", Format.Date8Format.format(pOneDay));//开始日期
	        xmlWriter.writeElementString("to", Format.Date8Format.format(pOneDay));//截至日期
	        xmlWriter.writeEndElement();

	        xmlWriter.writeStartElement("domaccount");
	        xmlWriter.writeElementClosed("transact");//交易对方账号
	        xmlWriter.writeElementClosed("transname");//对方账户名称
	        xmlWriter.writeEndElement();

	        xmlWriter.writeElementString("insid", this.getTransID());//客户申请号非空
	        xmlWriter.writeStartElement("multidata");
	        xmlWriter.writeStartElement("confirmdata");
	        xmlWriter.writeElementString("actacn", p_reqReceipt.actNum);//查询账号
	        
	        //联行号，可空，数码5位，联行号有对应的省行联行号，旧线账号建议上送
	        if(StringHelper.hasAnyChar(p_reqReceipt.areaCode) && p_reqReceipt.areaCode.length() == 5){
	        	xmlWriter.writeElementString("ibknum", p_reqReceipt.areaCode);//联行号
	        }else{
	        	xmlWriter.writeElementClosed("ibknum");//联行号
	        }
	        xmlWriter.writeEndDocument();
	        String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
	        if (tmpStrRet[0].length() == 0) {
	            StringBuilder tmpSbMsg = new StringBuilder();
	            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
	            if (tmpBkReader != null) {
	                String trspcod = tmpBkReader.getFirstText("/bocb2e/trans/trn-"+receiptTrnCode+"-rs/status/rspcod");
	                String trspmsg = tmpBkReader.getFirstText("/bocb2e/trans/trn-"+receiptTrnCode+"-rs/status/rspmsg");
	                if ("B001".equals(trspcod)) {
	                    String rspcod = tmpBkReader.getFirstText("/bocb2e/trans/trn-"+receiptTrnCode+"-rs/"+receiptTrnCode+"-rs/status/rspcod");
	                    String rspmsg = tmpBkReader.getFirstText("/bocb2e/trans/trn-"+receiptTrnCode+"-rs/"+receiptTrnCode+"-rs/status/rspmsg");
	                    if ("B001".equals(rspcod)) {
	                        String fileName = tmpBkReader.getFirstText("/bocb2e/trans/trn-"+receiptTrnCode+"-rs/"+receiptTrnCode+"-rs/filename");//名称
	                        WriteBankLogLn("待下载文件名："+fileName);
	                        DownFileRecord downRd = new DownFileRecord();
	                        downRd.srcSys = this.bankFront.bankCode;
	                        downRd.bank = "104";
	                        downRd.bankFrontCode = this.bankFront.code;
	                        downRd.busDate = Integer.parseInt(Format.Date8Format.format(pOneDay));
	                        downRd.downState = "1";
	                        downRd.filePath = fileName;
	                        downRd.ownAct = p_reqReceipt.actNum;
	                        DownFileHelper dHelper = null;
	                        try{
	                        	Date nowDay = new Date();
	                        	//此时采用当日，记录待下载文件，通过计划任务运行下载
	                        	dHelper = new DownFileHelper(p_reqReceipt.reqHeader.tenant, nowDay);
		                        int rowsAff = dHelper.insertIfNotExist(downRd);
		                        String aLog = "写入文件下载记录表行数："+rowsAff;
		                        if(rowsAff == 1){
		                        	aLog += "，记录写入成功";
		                        	BOC01TaskReceiptPro.resetDelayCounter();
		                        }else if(rowsAff == 0){
		                        	aLog += "，记录已存在";
		                        }
		                        WriteBankLogLn(aLog);
	                        }catch(Exception ex){
	                        	WriteBankLogLn(ex);
	                        }finally{
	                        	if(dHelper!=null){
	                        		dHelper.close();
	                        	}
	                        }
	                    } else {
	                        WriteBankLogLn(rspmsg);
	                    }
	                } else {
	                    WriteBankLogLn(trspmsg);
	                }
	            } else {
	                WriteBankLogLn(tmpSbMsg.toString());
	            }
	        } else {
	            WriteBankLogLn(tmpStrRet[1]);
	        }
		} catch (Exception e) {
            WriteBankLogLn(e);
        }
	}
}
